package com.example.demo.controller;

import com.example.demo.data.ResultDate;
import com.example.demo.pojo.User;
import com.example.demo.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;


@RestController
@Transactional  //开启事务回滚
public class LoginController {

    @Autowired
    private UserService userService;

    @RequestMapping(value = "login",method = RequestMethod.POST)
    public ResultDate<User> getUsers(HttpServletRequest request, String loginName, String passWord){

        //通过用户名和密码查询用户
        User user = userService.getUserByLoginAndPwd(loginName, passWord);

        if (user !=null ){
            ResultDate<User> userResultDate = new ResultDate<>();
            userResultDate.setMsg("登录成功~");
            userResultDate.setObj(user);
            //存储登录的session值
            request.getSession().setAttribute("user",user);

            return userResultDate;
        }

        return new ResultDate<>(-1,200,"用户名或密码输入有误！请重新输入");
    }

    //获取session值
    @RequestMapping("getSession")
    public Object getSession(HttpServletRequest request){

        return request.getSession().getAttribute("user");

    }




}
